package com.seata.demo.account.service.impl;

import com.seata.demo.account.entity.Account;
import com.seata.demo.account.mapper.AccountMapper;
import com.seata.demo.account.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public void debit(String userId, BigDecimal money) {
        int result = accountMapper.debit(userId, money);
        if (result <= 0) {
            throw new RuntimeException("账户余额不足，扣减失败");
        }
    }
    
    @Override
    public void revert(String userId, BigDecimal money) {
        // 实际应用中应该实现具体的余额恢复逻辑
        Account account = accountMapper.selectByUserId(userId);
        if (account != null) {
            // 这里简化处理，实际应根据业务场景实现
        }
    }

    // TCC模式方法
    @Override
    public boolean tryDebit(String userId, BigDecimal money) {
        // 尝试扣减，先冻结金额
        int result = accountMapper.freeze(userId, money);
        return result > 0;
    }

    @Override
    public boolean confirmDebit(String userId, BigDecimal money) {
        // 确认扣减，将冻结的金额实际扣除
        int result = accountMapper.confirmDebit(userId, money);
        return result > 0;
    }

    @Override
    public boolean cancelDebit(String userId, BigDecimal money) {
        // 取消扣减，解冻金额
        int result = accountMapper.unfreeze(userId, money);
        return result > 0;
    }
}
